/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kenny.wiki.ejb.entity.facade;

import com.kenny.wiki.ejb.entity.Title;
import com.kenny.wiki.ejb.entity.facade.remote.TitleFacadeRemote;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Kenny Lin
 */
@Stateless
public class TitleFacade extends AbstractFacade<Title> implements TitleFacadeRemote {
    @PersistenceContext(unitName = "Kenny-Wiki-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public TitleFacade() {
        super(Title.class);
    }

    public List<Title> findByCategoryOrderByView(int categoryId){
        String sql = "select * from title where category_id="+categoryId+" order by title_view desc";
        Query query = em.createNativeQuery(sql,Title.class);
        List<Title> titles = query.getResultList();
        if(titles.isEmpty()){
            return null;
        }else{
            return titles;
        }
    }

    public List<Title> findByCategoryOrderByEdit(int categoryId){
        String sql = "select * from title where category_id="+categoryId+" order by title_edit desc";
        Query query = em.createNativeQuery(sql,Title.class);
        List<Title> titles = query.getResultList();
        if(titles.isEmpty()){
            return null;
        }else{
            return titles;
        }
    }

    public List<Title> findByUserId(int userId){
        return getEntityManager().createNamedQuery("Title.findByUserId")
                .setParameter("userId", userId).getResultList();
    }

    public Title findByTitleName(String titleName){
        return (Title)getEntityManager().createNamedQuery("Title.findByTitleName")
                .setParameter("titleName", titleName).getSingleResult();
    }
}
